package LC;

import java.util.Arrays;
import java.util.Scanner;

/**
 * https://leetcode.com/problems/spiral-matrix-ii/description/
 * Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
 * For example,
 * Given n = 3,
 * You should return the following matrix:
 * [
 * [ 1, 2, 3 ],
 * [ 8, 9, 4 ],
 * [ 7, 6, 5 ]
 * ]
 */
public class LC_059_SpiralMatrixII_Loop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int[][] a = Solution.generateMatrix(n);
            System.out.println(Arrays.deepToString(a)
                    .replaceAll("], \\[", "\n")
                    .replaceAll("\\[", "")
                    .replaceAll("]", "")
                    .replaceAll(", ", "\t"));
        }
        sc.close();
    }

    static class Solution {
        static int[][] generateMatrix(int n) {
            int startx = 0, starty = 0, endx = n - 1, endy = n - 1;
            int[][] ans = new int[n][n];
            int count = 1;

            while (startx <= endx && starty <= endy) {
                for (int i = startx; i <= endx; i++)
                    ans[starty][i] = count++;
                starty++;

                for (int i = starty; i <= endy; i++)
                    ans[i][endx] = count++;
                endx--;

                for (int i = endx; i >= startx; i--)
                    ans[endy][i] = count++;
                endy--;

                for (int i = endy; i >= starty; i--)
                    ans[i][startx] = count++;
                startx++;
            }
            return ans;

        }

    }

}
